package com.antler.smt.portal.service.impl;

import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.OrderConstant;
import com.antler.smt.entity.*;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.*;
import com.antler.smt.request.portal.OrderReq;
import com.antler.smt.request.portal.OrderTestFileReq;
import com.antler.smt.response.admin.GetOrderListResp;
import com.antler.smt.response.admin.GetOrderLogisticsResp;
import com.antler.smt.response.admin.GetUserListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.response.portal.GetOrderCommentListResp;
import com.antler.smt.response.portal.GetOrderDetailResp;
import com.antler.smt.service.portal.OrderService;
import com.antler.smt.utils.DateUtil;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 订单接口实现
 *
 * @author zhangyi
 * @date 2018/3/28 14:07
 */
@Repository
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderEntityMapper orderEntityMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private AttachmentEntityMapper attachmentEntityMapper;

    @Autowired
    private RequirementEntityMapper requirementEntityMapper;
    /**
     * 获取订单列表信息
     *
     * @param id 订单id值
     * @return
     */
    @Override
    public Result<GetOrderListResp> getOrderList(Long id,Long memberId) {
        Result result = null;
        OrderEntity orderEntity = orderEntityMapper.selectByPrimaryKey(id);

        //获取 服务商名字 项目专员名字 采购商留言（发布需求备注）收货地址
        GetOrderDetailResp getOrderDetailResp = orderInfoMapper.orderDetailInfo(id);

        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(memberId);

        if(memberEntity != null){
            //判断类型
            Integer type = memberEntity.getType();

            //屏蔽对应的地址信息
            if(1 == type){
                getOrderDetailResp.setCountryName(null);
                getOrderDetailResp.setCityName(null);
                getOrderDetailResp.setProvinceName(null);
                getOrderDetailResp.setDetailAddress(null);
            }else if(2 == type){
                getOrderDetailResp.setConsigneeAdress(null);
                getOrderDetailResp.setConsigneeName(null);
                getOrderDetailResp.setConsigneePhone(null);
            }

        }

        AttachmentEntity attachmentEntity = attachmentEntityMapper.selectByPrimaryKey(orderEntity.getTestReportAttachmentId());

        if(attachmentEntity != null) {
            getOrderDetailResp.setReportName(attachmentEntity.getFileName());
        }

        List<Object> list = new ArrayList<>();
        list.add(orderEntity);
        list.add(getOrderDetailResp);

        result = new Result(list);
        return result;
    }

    /**
     *  采购商确认收货
     *
     * @param orderId
     * @return
     */
    @Override
    public Result<ResultCodeEnum> getGoods(Long orderId) {
        Result result = null;

        //创建采购商实体
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setId(orderId);

        //进度 0待对接服务商 1待付款 2待确认付款 3待生产完成  4待收货 6待评价 7待付款给服务商 8结束 100驳回
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_COMMENT);

        //更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);

        if(0 == i){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     * 获取采购商分类订单(全部订单，已完成，未完成，未通过)
     *
     * @param memberId 当前会员id
     * @param orderStatus 订单状态
     * @return
     */
    @Override
    public Result<GetOrderListResp> getPurchaserOrderClassifyInfo(Long memberId, Integer orderStatus) {
        Result result = null;

        //创建返回订单链表
        List<GetOrderListResp> orderListResps = new LinkedList<>();

        //获取采购商的全部订单
        List<GetOrderListResp> getOrderListResps =  orderInfoMapper.selectOrderByMember(memberId);

        //返回指定状态订单链表
        for (GetOrderListResp orderList : getOrderListResps){

            //插入图片
            AttachmentEntity attachmentEntity = attachmentEntityMapper.selectByPrimaryKey(orderList.getTestReportAttachmentId());

            if(attachmentEntity != null) {
                orderList.setReportName(attachmentEntity.getFileName());
            }

            //项目专员id
            Long connectUserId = orderList.getConnectUserId();
            //商务专员id
            Long businessAffairsUserId = orderList.getBusinessAffairsUserId();
            //项目专员实体
            GetUserListResp userInfo = userInfoMapper.getUserInfo(connectUserId);
            if(userInfo != null) {
                //插入项目专员的真实姓名
                orderList.setRealName(userInfo.getRealName());
            }
            GetUserListResp businessUserInfo = userInfoMapper.getUserInfo(businessAffairsUserId);
            if(businessUserInfo  != null) {
                orderList.setBusinessUserName(businessUserInfo.getRealName());
            }
            if((orderList.getStatus() != 100 && orderStatus != 100)) {
                //服务商id
                Long supplierId = orderList.getSupplierId();

                SupplierEntity supplierEntity = supplierEntityMapper.selectByPrimaryKey(supplierId);

                if(orderList.getStatus() != 0 && orderStatus != 0) {

                    if(supplierEntity != null) {
                        //服务商用户实体
                        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(supplierEntity.getMemberId());

                        //插入服务商昵称
                        orderList.setNickName(memberEntity.getNickName());

                    }else{
                        orderList.setNickName("服务商不存在！");
                    }

                }
            }

            if(orderStatus.equals(OrderConstant.ORDER_WAIT_PAY_SUPPLIER) || orderStatus.equals(OrderConstant.ORDER_END)){
                //已完成
                if(orderList.getStatus().equals(OrderConstant.ORDER_WAIT_PAY_SUPPLIER)||
                        orderList.getStatus().equals(OrderConstant.ORDER_END)) {
                    orderListResps.add(orderList);
                }
            }else if(OrderConstant.ORDER_FAIL.equals(orderStatus)){
                if(orderList.getStatus().equals(OrderConstant.ORDER_FAIL)) {
                    //未通过
                    orderListResps.add(orderList);
                }
            }else if(orderList.getStatus() <= OrderConstant.ORDER_WAIT_COMMENT){
                //未完成
                orderListResps.add(orderList);
            }
        }

        result = new Result(orderListResps);

        return result;
    }

    /**
     *  获取其服务商的分类订单信息
     *
     * @param memberId 当前会员id
     * @param orderStatus
     * @return
     */
    @Override
    public Result<GetOrderListResp> getSupplierOrderClassifyInfo(Long memberId, Integer orderStatus) {
        Result result = null;

        List<GetOrderListResp> supplierOrderClassifyList = orderInfoMapper.getSupplierOrderClassifyList(memberId);

        //创建分类订单链表
        List<GetOrderListResp> orderListResps = new LinkedList<>();

        for (GetOrderListResp orderList :supplierOrderClassifyList){
            AttachmentEntity attachmentEntity = attachmentEntityMapper.selectByPrimaryKey(orderList.getTestReportAttachmentId());
            if(attachmentEntity != null) {
                orderList.setReportName(attachmentEntity.getFileName());
            }

            //插入实际预计交货时间
            if(orderList.getStatus() > OrderConstant.ORDER_WAIT_SURE_PAYMENT) {
                Long orderId = orderList.getId();
                OrderEntity orderEntity = orderEntityMapper.selectByPrimaryKey(orderId);
                //支付审核时间
                Date payAuditTime = orderEntity.getPayAuditTime();
                RequirementEntity requirementEntity = requirementEntityMapper.selectByPrimaryKey(orderEntity.getRequirementId());
                //获取交期/小时
                Integer endline = requirementEntity.getEndline();
                Long endTime = new Long(endline * 60 * 60 * 1000);
                //预定时间：交期+项目专员审核金额后的时间
                orderList.setReserveTime(DateUtil.stampToDate(endTime + payAuditTime.getTime()));
                //实际交货时间：采购商收货的时间
                if (OrderConstant.ORDER_WAIT_COMMENT <= orderEntity.getStatus() && !orderEntity.getStatus().equals(OrderConstant.ORDER_FAIL)) {
                    orderList.setActualTime(orderEntity.getUpdateTime());
                }
            }

            if(orderList.getStatus().equals(orderStatus) &&
                    orderStatus.equals(OrderConstant.ORDER_END)){
                //已完成
                orderListResps.add(orderList);
            }else if(orderList.getStatus() >= OrderConstant.ORDER_WAIT_JOIN_SUPPLIER
                    && orderList.getStatus() <= OrderConstant.ORDER_WAIT_PAY_SUPPLIER &&
                    orderStatus <= OrderConstant.ORDER_WAIT_PAY_SUPPLIER &&
                    orderStatus >= OrderConstant.ORDER_WAIT_JOIN_SUPPLIER){
                //未完成
                if(!orderList.getStatus().equals(OrderConstant.ORDER_WAIT_JOIN_SUPPLIER) &&
                        !orderList.getStatus().equals(OrderConstant.ORDER_WAIT_PAYMENT) &&
                        !orderList.getStatus().equals(OrderConstant.ORDER_WAIT_SURE_PAYMENT)) {
                    orderListResps.add(orderList);
                }
            }

        }
        result = new Result(orderListResps);
        return result;
    }

    /**
     * 采购商支付
     *
     * @param req
     * @return
     */
    @Override
    public Result<ResultCodeEnum> payStyle(OrderReq req,Long requirementId) {
        Result result = null;

        //创建订单实体
        OrderEntity orderEntity = new OrderEntity();

        //设置需求id
        orderEntity.setRequirementId(requirementId);

        //待确认付款
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_SURE_PAYMENT);

        //申请支付类型 1线下打款 2银联 3支付宝 4微信
        orderEntity.setPayApplyType(req.getPayApplyType());

        //申请支付金额
        orderEntity.setPayApplyAmmount(req.getPayApplyAmmount());

        //申请支付时间
        orderEntity.setPayApplyTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i = orderInfoMapper.updateOrderPayStyle(orderEntity);

        if(0 == i){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }

        return result;
    }

    /**
     *  发布需求后的最终报价
     *
     * @param orderId
     * @return
     */
    @Override
    public Result<Long> lastOffer(Long orderId) {
        Result result = null;
        OrderEntity orderEntity = orderEntityMapper.selectByPrimaryKey(orderId);

        //获取其订单中的最终报价
        Long priceToPurchaser = orderEntity.getPriceToPurchaser();

        result = new Result(priceToPurchaser);

        return result;
    }

    /**
     * 上传文件附件
     *
     * @param orderTestFileReq
     * @return
     */
    @Override
    public Result updateUploadTestFile(OrderTestFileReq orderTestFileReq) {
        int i = orderInfoMapper.updateUploadTestFile(orderTestFileReq);
        return 0 == i ? new Result(ResultCodeEnum.APPEND_DATA_ERROR):new Result(ResultCodeEnum.OPERATION_SUCCESS);
    }

    /**
     * 获取订单内检验报告
     *
     * @param orderId
     * @return
     */
    @Override
    public Result getOrderFileInfo(Long orderId) {
        Result result = null;

        List<String> orderFile = orderInfoMapper.getOrderFile(orderId);

        if(orderFile != null){
            result = new Result(orderFile);
        }else{
            result  = new Result(ResultCodeEnum.APPEND_DATA_ERROR,
                    "获取检验报告错误！");
        }
        return result;
    }
}
